<template>
  <div class="main">
    <el-button type="success" @click="create"> 创建模板头 </el-button>
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-[99/100] pt-[12px] overflow-auto"
    >
      <el-form-item label="关键字" prop="keyword">
        <el-input
          v-model="form.keyword"
          placeholder="搜索关键字"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="success"
          :icon="useRenderIcon('ri:search-line')"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      show-overflow-tooltip
      stripe
      border
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column align="center" prop="id" label="ID" width="100" />

      <el-table-column align="center" label="名称">
        <template #default="scope">
          {{ scope.row.title || "--" }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="描述">
        <template #default="scope">
          {{ scope.row.description || "--" }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="createTime"
        :formatter="val => handleAutoUTC8(val.createTime)"
        label="创建时间"
      />
      <el-table-column
        align="center"
        prop="updateTime"
        :formatter="val => handleAutoUTC8(val.updateTime)"
        label="更新时间"
      />
      <el-table-column label="操作" align="center" fixed="right" width="400">
        <template #default="scope">
          <el-button
            link
            type="success"
            size="small"
            @click="update(scope.row)"
          >
            更新
          </el-button>
          <el-button
            link
            type="success"
            size="small"
            :loading="scope.row.mapLoading"
            @click="mapping(scope.row.id)"
          >
            设置映射关系
          </el-button>
          <el-button
            link
            type="success"
            size="small"
            @click="setUser(scope.row)"
          >
            指定用户
          </el-button>
          <el-popconfirm
            width="220"
            :icon="InfoFilled"
            icon-color="#626AEF"
            title="确认删除该模板项吗？"
            @confirm="confirmStatus(scope.row.id)"
          >
            <template #reference>
              <el-button link type="danger" size="small"> 删除 </el-button>
            </template>
            <template #actions="{ confirm, cancel }">
              <el-button size="small" @click="cancel">取消</el-button>
              <el-button type="danger" size="small" @click="confirm">
                确定
              </el-button>
            </template>
          </el-popconfirm></template
        >
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 40, 50]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <AddTemplateDialog ref="addTemplateDialogRef" @refresh="onSearch" />
    <MappingTemplateDialog ref="mappingTemplateDialogRef" @refresh="onSearch" />
    <UserTemplateDialog ref="userTemplateDialogRef" @refresh="onSearch" />
  </div>
</template>

<script lang="ts" setup>
import { InfoFilled } from "@element-plus/icons-vue";
import { reactive, ref, onMounted } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Refresh from "@iconify-icons/ep/refresh";
import { message } from "@/utils/message";
import {
  getAdminTemplateList,
  deleteAdminTemplateHead,
  getAdminTemplateHead
} from "@/api/adminTemplateHeadApi";
import AddTemplateDialog from "./components/AddTemplateDialog.vue";
import MappingTemplateDialog from "./components/MappingTemplateDialog.vue";
import UserTemplateDialog from "./components/UserTemplateDialog.vue";
import { handleAutoUTC8 } from "@/utils/tools";

const formRef = ref();
const loading = ref(false);
const form = reactive({
  keyword: ""
});
const pagination = reactive({
  total: 0,
  pageSize: 10,
  currentPage: 1
});
const addTemplateDialogRef = ref();
const update = (row: any) => {
  addTemplateDialogRef.value?.open(row);
};
const create = () => {
  addTemplateDialogRef.value?.open();
};
const mappingTemplateDialogRef = ref();
const mapping = async (id: string) => {
  const index = tableData.value.findIndex((item: any) => item.id === id);
  tableData.value[index].mapLoading = true;
  try {
    const { data } = await getAdminTemplateHead(id);
    const { template, items = [] } = data;
    mappingTemplateDialogRef.value?.open({
      ...template,
      itemIds: items.map((item: any) => item.id)
    });
  } catch (error) {
    console.log(error);
  } finally {
    tableData.value[index].mapLoading = false;
  }
};
const userTemplateDialogRef = ref();
const setUser = (row: any) => {
  userTemplateDialogRef.value?.open(row);
};
const confirmStatus = async (id: string) => {
  try {
    const { message: text } = await deleteAdminTemplateHead(id);
    message(text || "操作成功", { type: "success" });
    onSearch();
  } catch (error) {
    console.log(error);
  }
};

const tableData = ref([]);
const onSearch = async () => {
  try {
    loading.value = true;

    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      ...form
    };
    const { data } = await getAdminTemplateList(params);
    const { records, total, size, current } = data;
    tableData.value = records.map((item: any) => {
      return {
        ...item,
        mapLoading: false
      };
    });
    pagination.total = total;
    pagination.pageSize = size;
    pagination.currentPage = current;
  } catch (error) {
    message("获取数据失败", { type: "error" });
    console.log(error);
  } finally {
    loading.value = false;
  }
};
const handleSizeChange = (val: number) => {
  pagination.currentPage = 1;
  pagination.pageSize = val;
  onSearch();
};
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  onSearch();
};
const resetForm = formEl => {
  if (!formEl) return;
  formEl.resetFields();
  pagination.currentPage = 1;
  onSearch();
};
onMounted(() => {
  onSearch();
});
</script>
<style lang="scss" scoped>
.main {
  padding: 20px;
  background-color: #fff;
  .el-pagination {
    margin-top: 20px;
    justify-content: flex-end;
  }
}
</style>
